package com.example.wyh.intelcheckbash;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.bluetoothchat.*;
import com.example.wyh.intelcheckbash.bug.BugListRecordActivity;
import com.example.wyh.intelcheckbash.common.CommonUtil;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.product_visit.ProductVisitListActivity;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.task.DownloadTaskActivity;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;
import com.example.wyh.intelcheckbash.task.UploadCheckedTaskActivity;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;
//import com.umeng.analytics.MobclickAgent;
//import com.umeng.commonsdk.UMConfigure;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {

//    private String mDeviceToken;
    public ImageView batteryItem;
    boolean isLogoutApp = false;
    String mConnectDeviceAddress = null;
    public String tempTest = null;
//    BluetoothChatFragment mFragment;
    //将同步内容下方到if内部，提高了执行的效率，不必每次获取对象时都进行同步，只有第一次才同步，创建了以后就没必要了。
    private static volatile BluetoothChatFragment mFragment=null;
    private static volatile boolean isConnectedInFail=false;
    public static  BluetoothChatFragment getInstance(){
        if(mFragment==null){
            synchronized(BluetoothChatFragment .class){
                if(mFragment==null){
                    mFragment=new BluetoothChatFragment ();
                }
            }
        }
        return mFragment;
    }
    public static boolean getIsConnectedInFail()
    {
        return isConnectedInFail;
    }
    public static void setIsConnectedInFail(boolean isConnected)
    {
        isConnectedInFail = isConnected;
    }

    public void updateBatteryStatus()
    {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    ViewGroup.LayoutParams lp = batteryItem.getLayoutParams();
                    lp.width = 213;
                    batteryItem.setLayoutParams(lp);
                    batteryItem.setImageResource(R.drawable.unconnect);
                    tempTest = null;
                }catch (Exception e)
                {
                    Log.e("===========error",e.getMessage());
                }

            }
        });

    }
    public void initBlueFragment()
    {
        if (isConnectedInFail == false)
        {
            mFragment.onDestroy();
            try {
                String bluetoothAddress = LocalStorage.getString(MainActivity.this,"blueToothAddress");
                if (mFragment.mIsConnectedBlueTooth == false && bluetoothAddress.length() != 0)
                {
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    isConnectedInFail = true;
                }
            }catch (Exception e)
            {

            }
        }
    }

    public void connectDeviceAddress()
    {
        if (mFragment != null && mFragment.mIsConnectedBlueTooth == false)
        {
            try {
                String bluetoothAddress = LocalStorage.getString(MainActivity.this,"blueToothAddress");
                if (bluetoothAddress.length() != 0)
                {
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    mConnectDeviceAddress = bluetoothAddress;
                    isConnectedInFail = false;
                }
            }catch (Exception e)
            {
//                MobclickAgent.reportError(MainActivity.this,e.getMessage());
                Log.e("bluetooth",e.getMessage());
            }

        }
        else
        {
            Log.e("=================","连接成功");
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
//        MobclickAgent.onResume(MainActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(MainActivity.this);
    }

    // 为了获取结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1

        if (resultCode == 1007)
        {
            //设置页面发过来的
            mConnectDeviceAddress = data.getStringExtra("mConnectDeviceAddress");
        }
        if (requestCode == 1007)
        {
            if (!isLogin()) {
                Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                loginIntent.putExtra("deviceToken",TelephonyMgr.getDeviceId());
                startActivityForResult(loginIntent,999);
            } else {
                initViews();
            }
        }
        Log.e("resultCode:requestCode",resultCode + ":"+requestCode);
        if (requestCode == 999)
        {
            if (isLogin()) {
                initViews();
            }
        }
    }

    public void initVersionCodeInFooter()
    {
        TextView main_footer_version_name = (TextView)findViewById(R.id.main_footer_version_name);
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            main_footer_version_name.setText("颐达科技 "+appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch blockd
            e.printStackTrace();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SysExitUtil.activityList.add(MainActivity.this);

        initVersionCodeInFooter();


//        UMConfigure.setLogEnabled(true);
//        UMConfigure.setEncryptEnabled(false);
//        MobclickAgent.setCatchUncaughtExceptions(true);
//        MobclickAgent.setScenarioType(MainActivity.this, MobclickAgent.EScenarioType.E_DUM_NORMAL);
//        MobclickAgent.setSessionContinueMillis(1000);

        Log.e("dangqianshijian",HttpUtil.getCurrentDateString());
        mFragment = null;
        mFragment = getInstance();
        mFragment.setContext(MainActivity.this);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.sample_content_fragment_temp_therm, mFragment);
        transaction.commit();

//        if (savedInstanceState == null) {

//        }
        if (!isLogin()) {
            Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
            startActivityForResult(loginIntent,999);
        } else {
            initViews();
        }

    }


    public ImageView judgeIsUpload()
    {
        ImageView uploadButton = (ImageView)findViewById(R.id.upload_task_btn);
        uploadButton.setImageResource(R.drawable.upload_main);
        TextView unUploadNumber = (TextView)findViewById(R.id.unUploadNumber);
        unUploadNumber.setVisibility(View.GONE);
        JSONArray allNeedToUploadData = getNeedUploadData();
        Log.e("allNeedToUploadData",allNeedToUploadData.toString());
        if (allNeedToUploadData.length() > 0)
        {
            uploadButton.setImageResource(R.drawable.upload_main_tag);
            unUploadNumber.setVisibility(View.VISIBLE);
            unUploadNumber.setText(allNeedToUploadData.length()+"");
        }
        return uploadButton;
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        if (hasFocus == true)
        {
            judgeIsUpload();
            connectDeviceAddress();
            try {
                if (mFragment != null && mFragment.mIsConnectedBlueTooth == true)
                {
                    updatebatteryLevel();
                }
            }catch (Exception e)
            {
                Log.e("onWindowFocusChanged--updatebatteryLevel",e.getMessage());
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
            activityMgr.restartPackage(getPackageName());

            LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
            final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                    null);

            final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setTitle("").setView(layout)
                    .setPositiveButton("",  new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setNegativeButton("", null).show();

            TextView alert_title = (TextView)layout.findViewById(R.id.alert_title);
            alert_title.setText("确认退出程序吗？");
            Button confirm = (Button)layout.findViewById(R.id.alert_confirm);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                    isLogoutApp = true;
                    int siz=SysExitUtil.activityList.size();
                    try {
                        String bluetoothAddress = LocalStorage.getString(MainActivity.this,"blueToothAddress");
                        if (mFragment.mIsConnectedBlueTooth == true && bluetoothAddress.length() != 0)
                        {
                            mFragment.connectDeviceWithAddress(bluetoothAddress);
                        }
                    }catch (Exception e)
                    {

                    }
                    try {
                        mFragment.onDestroy();
                    }catch (Exception e)
                    {
                        Log.e("mFragment is null",e.getMessage());
                    }

                    for(int i=0;i<siz;i++){
                        if(SysExitUtil.activityList.get(i)!=null){
                            ((Activity) SysExitUtil.activityList.get(i)).finish();
                        }
                    }
                }
            });
            Button cancle = (Button)layout.findViewById(R.id.alert_cancle);
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
        }
        return super.onKeyDown(keyCode, event);
    }

    public void showBatteryLevel(byte[] batteryLevelData)
    {
        String[] arrData = CommonUtil.bytesToHexStrings(batteryLevelData);
        int high = Integer.parseInt(arrData[0],16);
        int low = Integer.parseInt(arrData[1],16);
        double batteryLevel = (high*256+low)/100.0;
        double battery = (batteryLevel-3.47)/(4.19 - 3.47);
//        Log.e("电量是",battery + "");

        batteryItem.setMaxWidth(40);
        ViewGroup.LayoutParams lp = batteryItem.getLayoutParams();
        lp.width = 116;
        batteryItem.setLayoutParams(lp);
        if (battery < 0.15)
        {
            batteryItem.setImageResource(R.drawable.battery15);
        }
        else if (battery < 0.25)
        {
            batteryItem.setImageResource(R.drawable.battery25);
        }
        else if (battery < 0.50)
        {
            batteryItem.setImageResource(R.drawable.battery50);
        }
        else if (battery < 0.75)
        {
            batteryItem.setImageResource(R.drawable.battery75);
        }
        else
        {
            batteryItem.setImageResource(R.drawable.battery100);
        }
        if (tempTest == null)
        {
            return;
        }
        else if (tempTest.equals("testThermometric"))
        {
            Intent thermome = new Intent(MainActivity.this, ThermometricActivity.class);
            startActivityForResult(thermome,1);
        }
        else if (tempTest.equals("testSeismic"))
        {
            Intent seis = new Intent(MainActivity.this, SeismicActivity.class);
            startActivityForResult(seis,1);
        }
        tempTest = null;
    }
    public void updatebatteryLevel()
    {
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                if (isLogoutApp == true) {
                    handler.removeCallbacks(this);
                    return;
                }
                mFragment.setTestType("testBatteryLevel");
                byte[] dataTestBatteryLevel = new byte[] { 0x42, 0x4C, 0x23 };//BL
                mFragment.sendMessage(dataTestBatteryLevel);
            }
        };
        handler.postDelayed(runnable,0);

    }
    private  boolean isLogin(){
        JSONObject User =  LocalStorage.getObject(MainActivity.this, "User");
        String reviceInfo =  LocalStorage.getByteString(MainActivity.this, "reciveInfo");
        Log.e("User",User.toString());
        TextView userNameText = (TextView)findViewById(R.id.username_main);
        TextView departmentText = (TextView)findViewById(R.id.department_main);
        if (User.length() > 0)
        {
            try {
                String userName = User.getString("usernamecn");
                String deptName = User.getString("deptname");
                userNameText.setText(userName);
                departmentText.setText(deptName);
            }
            catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        Log.e("reciveInfo","=="+reviceInfo.toString());
        return  User.length() > 0;
    }


    private void initViews() {

        batteryItem = (ImageView)findViewById(R.id.image_battery_show);
        batteryItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFragment != null && mFragment.mIsConnectedBlueTooth == true)
                {
                    updatebatteryLevel();
                }
            }
        });
        initThermometricButton();
        initSeismicButton();
        initTaskCheckBtn();
        initDownloadTaskBtn();
        initStatisticalCheckButton();
        initSettingButton();
        initUploadResultButton();
        initBugRecordButton();
        initProductVisitListButton();

//        connectDeviceAddress();
    }

    public JSONArray getNeedUploadData(){

        JSONArray completeXmInfo = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(MainActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "user_id = '" + LocalStorage.getUserXtm(MainActivity.this) + "'"
//                + " and time = '" + HttpUtil.getCurrentDateString() +"'"
//                + " and isUploadSuccess = '0'" ;
        String query = "user_id = '" + LocalStorage.getUserXtm(MainActivity.this) + "'"
                + " and isUploadSuccess = '0'" ;
        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);
            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        completeXmInfo.put(new JSONObject(data));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    private void initUploadResultButton()
    {
        ImageView uploadButton = judgeIsUpload();
        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JSONObject User =  LocalStorage.getObject(MainActivity.this, "User");
                String yhxtm = "";
                try {
                    yhxtm = User.getString("yhxtm");
                }catch (JSONException e)
                {
                    throw new RuntimeException(e);
                }
                Intent uploadTask = new Intent(MainActivity.this, UploadCheckedTaskActivity.class);
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                uploadTask.putExtra("deviceToken",TelephonyMgr.getDeviceId());
                uploadTask.putExtra("yhxtm",yhxtm);
                startActivity(uploadTask);
            }
        });
    }
    private void initDownloadTaskBtn()
    {
        ImageView downloadBtn = (ImageView)findViewById(R.id.download_task_btn);
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JSONObject User =  LocalStorage.getObject(MainActivity.this, "User");
                String yhxtm = "";
                try {
                    yhxtm = User.getString("yhxtm");
                }catch (JSONException e)
                {
                    throw new RuntimeException(e);
                }
                Intent downloadTask = new Intent(MainActivity.this, DownloadTaskActivity.class);
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                downloadTask.putExtra("deviceToken",TelephonyMgr.getDeviceId());
                downloadTask.putExtra("yhxtm",yhxtm);
                startActivity(downloadTask);
            }
        });
    }

    private void initTaskCheckBtn()
    {
        ImageView task_check_btn = (ImageView) findViewById(R.id.task_check_btn);
        task_check_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
//                if (mFragment.mIsConnectedBlueTooth == false)
//                {
//                    mFragment.mChatService.start();
//                }
                JSONObject User =  LocalStorage.getObject(MainActivity.this, "User");
                String yhxtm = "";
                try {
                    yhxtm = User.getString("yhxtm");
                }catch (JSONException e)
                {
                    throw new RuntimeException(e);
                }
                Intent taskCheck = new Intent(MainActivity.this, TaskCheckActivity.class);
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                taskCheck.putExtra("deviceToken",TelephonyMgr.getDeviceId());
                taskCheck.putExtra("yhxtm",yhxtm);
                startActivity(taskCheck);
            }
        });
    }
    public void testThermomConnectBlueTooth()
    {
        String bluetoothAddress = LocalStorage.getString(MainActivity.this,"blueToothAddress");
        if (bluetoothAddress.length() == 0)
        {
            HttpUtil.showToast(MainActivity.this,"请先在设置页面连接蓝牙设备",1000);
        }else
        {
            connectDeviceAddress();
            tempTest = "testThermometric";
        }
    }
    public void testSeismicConnectBlueTooth()
    {
        String bluetoothAddress = LocalStorage.getString(MainActivity.this,"blueToothAddress");
        if (bluetoothAddress.length() == 0)
        {
            HttpUtil.showToast(MainActivity.this,"请先在设置页面连接蓝牙设备",1000);
        }else {
            tempTest = "testSeismic";
            connectDeviceAddress();
        }
    }

    private void initThermometricButton() {
        ImageView thermometric_btn = (ImageView) findViewById(R.id.thermometric_btn);
        thermometric_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try
                {
                    if (mFragment != null && mFragment.mIsConnectedBlueTooth == true)
                    {
                        Intent thermome = new Intent(MainActivity.this, ThermometricActivity.class);
                        startActivityForResult(thermome,1);
                    }
                    else
                    {
                        Log.e("testThermomConnectBlueTooth else","==============");
                        testThermomConnectBlueTooth();
                    }
                }catch (Exception e)
                {
                    Log.e("testThermomConnectBlueTooth else","=============="+e.getMessage());

                    testThermomConnectBlueTooth();
                }

            }
        });

    }

    private void initSeismicButton() {
        ImageView seismic_btn = (ImageView) findViewById(R.id.seismic_btn);
        seismic_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try
                {
                    if (mFragment != null && mFragment.mIsConnectedBlueTooth == true)
                    {
                        try {
                            Intent seis = new Intent(MainActivity.this, SeismicActivity.class);
                            startActivityForResult(seis,1);
                        }
                        catch (Exception e)
                        {
                            Log.e("========",e.getMessage());
                        }
                    }
                    else
                    {
                        testSeismicConnectBlueTooth();
                    }
                }catch (Exception e)
                {
                    testSeismicConnectBlueTooth();
                }


            }
        });

    }
    private void initStatisticalCheckButton() {
        ImageView statistical_check_btn = (ImageView) findViewById(R.id.statistical_check_btn);
        statistical_check_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent statis = new Intent(MainActivity.this, StatisticalCheckActivity.class);
                startActivity(statis);
            }
        });

    }
    public  void  initSettingButton(){
        ImageView setting_btn = (ImageView) findViewById(R.id.setting_btn);
        setting_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startActivity();
                Intent setting = new Intent(MainActivity.this, SettingActivity
                        .class);
                setting.putExtra("mConnectDeviceAddress",mConnectDeviceAddress);
                startActivityForResult(setting,1007);
            }
        });
    }

    public  void  initBugRecordButton(){
        ImageView about_btn = (ImageView) findViewById(R.id.bug_record_btn);
        about_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent bug_record_activity = new Intent(MainActivity.this,BugListRecordActivity.class);
                startActivity(bug_record_activity);
            }
        });
    }

    public  void  initProductVisitListButton(){
        ImageView about_btn = (ImageView) findViewById(R.id.product_visit);
        about_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent product_visit_list_activity = new Intent(MainActivity.this,ProductVisitListActivity.class);
                startActivity(product_visit_list_activity);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
//        MenuItem logToggle = menu.findItem(R.id.menu_toggle_log);
//        logToggle.setVisible(findViewById(R.id.sample_output) instanceof ViewAnimator);
//        logToggle.setTitle(mLogShown ? R.string.sample_hide_log : R.string.sample_show_log);

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

}
